import cgi
import time
import json
import webapp2
import logging

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, coowner_payment
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler


class CoownerPayments(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(CoownerPayments, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return

        self.fields = {
                       'coowner': _('Coowner'), 
                       'immeuble': _('Tenement'), 
                       'date': _('Date'), 
                       'type': _('Type'),
                       'payment_num': _('Reference payment'), 
                       'amount': _('Amount'), 
                       'label': _('Label'), 
                       'period': _('Account period'),
                       'fundraising': _('Fundraising request'), 
                       'bankaccount' : _('Bank account'),
                       'bank_date' : _("Money received date"),
                       'cheque_date' : _("Check received date"),
                        'money_recived' : _('Money received'),
                       }
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self,  *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Coowner payments. %s' % imm.name),
                           'header': _('%s. Coowner payments.' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'coowner_payments',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/coowner_payments_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        cp = []
        for p in imm.period_concept_set.filter('close_accounting =', False):  
            for fr in p.fundraising_set.run():
                for c in fr.coowner_payment_set.run(): 
                    c_date = None
                    if c.cheque_date:
                        c_date = c.cheque_date.strftime("%d/%m/%y")
                    b_date = None
                    if c.bank_date:
                        b_date =  c.bank_date.strftime("%d/%m/%y")
                    mr = _('No')
                    if c.money_recived:
                        mr = _('Yes')
                    cp.append([str(c.fundraising), 
                               unicode(c.coowner), 
                               unicode(c.type), 
                               c_date,
                               c.payment_num,
                               b_date,
                               unicode('{:0,.2f}'.format(c.amount)),
                               unicode(mr),
                               str(c.key())])
        ret = {}
        ret['aaData'] = cp
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))

        ok_message = ''
        
        lo_l = []
        for lot in imm.lot_set.run():
            for lo in lot.owner_lots.run():
                lo_l.append(lo.owner)
        lo_l = functions.distinct(lo_l)
        
        fr_l = []
        for p in imm.period_concept_set.filter('close_accounting =', False).run():
            for fr in p.fundraising_set.run():
                fr_l.append(fr)
       
        CoownerPaymentForm = model_form(coowner_payment, exclude=['immeuble', 'lastchange_by', 'lastchange_date', 'money_recived', 'commited'])
            
        if self.request.method == 'GET':
            form = CoownerPaymentForm()
            form['coowner'].query = lo_l
            form['fundraising'].query = fr_l
            
        if self.request.method == 'POST':
            form = CoownerPaymentForm(self.request.POST)
            form['coowner'].query = lo_l
            form['fundraising'].query = fr_l
            
            if form.validate():
                save = True
                if form['type'].data != 'Carte Blue':
                    if not form['fundraising'].data:
                        save = False
                        msg = _("'Fundraising request' should be defined")
                        form['fundraising'].errors.append(msg)
                else:
                    if not form['period'].data:
                        save = False
                        msg = _("'Accounting period' should be defined")
                        form['period'].errors.append(msg)
                    if not form['bankaccount'].data:
                        save = False
                        msg = _("'Bank account' should be defined")
                        form['bankaccount'].errors.append(msg)
                    
                    if not form['payment_num'].data:
                        save = False
                        msg = _("'Reference paiement' should be defined")
                        form['payment_num'].errors.append(msg)
                if save:    
                    new_cp = coowner_payment(lastchange_by = self.au, 
                                             immeuble = imm, 
                                             coowner = form['coowner'].data,
                                             fundraising =  form['fundraising'].data,
                                             cheque_date = form['cheque_date'].data,
                                             bank_date = form['bank_date'].data,
                                             type = form['type'].data,
                                             amount = form['amount'].data
                                             )
                    
                    if form['type'].data == 'Carte Blue':
                        new_cp.bankaccount = form['bankaccount'].data
                        new_cp.period = form['period'].data

                    new_cp.payment_num = form['payment_num'].data
                    new_cp.put()
                    while not new_cp.is_saved():
                        time.sleep(2)
                
                    ok_message = _('Coowner payment was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        cp_key = kwargs.get('cp_id', "")
        ok_message = ''
        alert_message = ''
        info_message = ''
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        cp_obj = coowner_payment.get(cp_key)
        if not cp_obj: 
            self.redirect(webapp2.uri_for('mainpage'))
            return    
        form = []
        if cp_obj.commited and cp_obj.money_recived:
            alert_message = _("Landlord payment and cannot be updated")
        else:
            
            if cp_obj.commited:
                CoownerPaymentForm = model_form(coowner_payment, only=['bank_date'])
            else:
                CoownerPaymentForm = model_form(coowner_payment, only=['type', 'cheque_date', 'payment_num','bank_date'])
                
            if self.request.method == 'GET':
                form = CoownerPaymentForm(obj = cp_obj)
 
                
            if self.request.method == 'POST':
                form = CoownerPaymentForm(self.request.POST)
                op_type =  cp_obj.type
                if not cp_obj.commited:
                    op_type = form['type'].data
                
                chck_date = cp_obj.cheque_date
                if not cp_obj.commited:
                    chck_date = form['cheque_date'].data
                
                if form.validate():
                    save = True
                    if op_type == 'Carte Blue':
                        if not form['bank_date'].data:
                            save = False
                            msg = _("'Money received date' should be defined")
                            form['bank_date'].errors.append(msg)
                    else:
                        logging.info(chck_date)
                        if not chck_date:
                            save = False
                            msg = _("'Check received date' should be defined")
                            logging.info(msg)
                            form['cheque_date'].errors.append(msg)
                        if cp_obj.commited and not form['bank_date'].data:
                            save = False
                            msg = _("'Money received date' should be defined")
                            form['bank_date'].errors.append(msg)
                    if save:
                        form.populate_obj(cp_obj)
                        cp_obj.lastchange_by = self.au 
                        cp_obj.put()
                        ok_message = _('Coowner payment was saved.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields, 'alert_message': alert_message, 'info_message': info_message}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_commit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        cp_key = kwargs.get('cp_id', "") 
        cp_obj = coowner_payment.get(cp_key)
        if not cp_obj:
            self.object_does_not_exist()
            return
        
        ok_message = ''
        alert_message = ''
        info_message = ''
        
        if self.request.method == 'GET':
            if cp_obj.commited and cp_obj.money_recived:
                info_message = _('Landlord payment already processed')
            else:
                alert_message = _('Landlord payment will be commited and General Ledger will be updated')
            
        if self.request.method == 'POST':
            
            if cp_obj.commited and cp_obj.money_recived:
                info_message = _('Landlord payment already processed')
            else:
                res, msg = cp_obj.update_general_ledger(self.au)
                if res:
                    ok_message = _(msg)
                else:
                    alert_message = _(msg)
                
        template_values = {
            'ok_message': ok_message,
            'alert_message': alert_message,
            'info_message': info_message,
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
